package com.itrip.filter;

import com.alibaba.fastjson.JSONObject;
import com.itrip.dto.ResponseDTO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class LoginFilter implements Filter {

    @Resource
    RedisTemplate redisTemplate;

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //从http头中获取token判断其是否存在
        HttpServletRequest httpServletRequest=(HttpServletRequest)servletRequest;
        String token = httpServletRequest.getHeader("token");
        ResponseDTO responseDTO=null;

        if(token!=null&&token!=""){
            Boolean flag = redisTemplate.hasKey(token);
            if(flag){
                responseDTO=  new ResponseDTO(100,"有临牌",null);
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }else{
                responseDTO= new ResponseDTO(102,"令牌不对或失效",null);
            }
        }else {
             responseDTO= new ResponseDTO(102,"未登陆",null);
        }
        HttpServletResponse httpResponse=(HttpServletResponse)servletResponse;
        httpResponse.setContentType("text/html;charset=utf-8");
        PrintWriter writer = httpResponse.getWriter();
        writer.write(JSONObject.toJSONString(responseDTO));

    }

    @Override
    public void destroy() {

    }
}
